﻿using System;
using QD.Utill;
using QD.Snapshot.Core.Config;
using System.Windows.Forms;
using System.Threading;
using NSoup.Nodes;
using System.Text.RegularExpressions;
using NSoup.Select;

namespace QD.Snapshot.Core.BLL
{
    public class Search_ShenMa : SearchBase
    {
        public Search_ShenMa(TextBox textBox, int SleepTime)
        {
            this.textBox = textBox;
            this.SleepTime = SleepTime;
            this.copyform = "6";        //神马搜索引擎
            Echo("神马移动截图已启动");
        }

        static Model.TaskModel_360 taskModel = new Model.TaskModel_360();
        HttpRequest Http = new HttpRequest();
        string htmls, msg;
        public override void Search(string keyword, Model.Product product, Model.WebSite company)
        {

            string html = string.Empty;
            string msg = string.Empty;

            Thread.Sleep(SleepTime);
            Http.ClearCookie();
            Http.SetWapUserAgent();
            msg = Http.Requset(string.Format(Engine.URL_ShenMa, keyword), out html);

            IsCode_ShenMa = CheckCode(html);   //是否出现验证码

            if (msg.Length > 0)
            {
                Echo(string.Format("搜索 {0} 返回错误", keyword));
            }
            else if (IsCode_ShenMa)
            {
                EchoLog("code", "神马出现验证码");
                Thread.Sleep(1000);
            }
            else
            {
                Echo(string.Format("搜索 {0}", keyword));
                taskModel.itemid = product.itemid;
                taskModel.keyword = keyword;
                taskModel.company = company;
                taskModel.html = html;

                NumHelper.Instance.SetNumShenMa(1);    //统计搜索速度

                //CheckOrAdd(taskModel.html, taskModel.keyword, taskModel.itemid, taskModel.company);

                ThreadPool.QueueUserWorkItem(new WaitCallback(CheckOrAdd), taskModel);
            }
        }

        void CheckOrAdd(object obj)
        {
            Model.TaskModel_360 model = obj as Model.TaskModel_360;

            CheckOrAdd(model.html, model.keyword, model.itemid, model.company);

            model = null;
        }

        void CheckOrAdd(string html, string keyword, int itemid, Model.WebSite company)
        {
            NSoup.Nodes.Document doc = NSoup.NSoupClient.Parse(html);
            Regex r1 = new Regex(FixRegex(company.ShortName), RegexOptions.IgnoreCase);
            Regex r2 = new Regex(FixRegex(keyword), RegexOptions.IgnoreCase);
            Regex SiteName = new Regex(FixRegex(company.SiteName), RegexOptions.IgnoreCase);
            Regex Cellphone = new Regex(FixRegex(company.Cellphone), RegexOptions.IgnoreCase);
            Regex phone = new Regex(FixRegex(company.Phone), RegexOptions.IgnoreCase);

            CheckOrAdd(doc, r1, SiteName, Cellphone, phone, itemid, company.UserID, keyword);
        }

        void CheckOrAdd(Document doc, Regex r1, Regex SiteName, Regex Cellphone, Regex phone, int itemid, int userid, string keyword, int page = 1)
        {
            Element parent = doc.GetElementById("results");
            if (parent == null) return;
            
            HideElementList(parent.GetElementsByClass("ad-wolong-container"));      //清除 广告
            HideElement(parent.GetElementById("sc_cbs_1_2"));                       //清除排行、参数、评价
            HideElement(parent.GetElementById("sc_kg_recommend_n_1_3"));            //清除底关推荐
            HideElement(parent.GetElementById("sider"));                            //清除底部相关搜索
            HideElement(parent.GetElementById("Sc_Shopping_Etao_shopping_1_3"));    //清除热卖商品
            HideElement(parent.GetElementById("sc_gala_operation_topic_1_4"));      //清除图片banner
            HideElementList(parent.GetElementsByClass("recommend-txt-feedbtn"));    //清除可能需要的内容
            HideElementList(parent.GetElementsByClass("sc_text_recommend"));        //清除其他人还搜了
            HideElementList(parent.GetElementsByClass("dl-container"));             //清除喜欢推荐和好货清单
        

            Elements result = parent.Select(".c-container");

            int index = 0;
            bool isFirst = true;
            string nums_html = "";

            foreach (Element ele in result)
            {
                index++;

                if (r1.IsMatch(ele.Text()) || CheckShortNameList(ele.Text()) || CheckQJY(ele.Text(), SiteName, Cellphone, phone))
                {
                    string index_key = GetMd5(ele.GetElementsByTag("c-header-title").Text); //第几行的key,更新时，用来确定更新哪一行
                    string platform = GetPlatform(ele.Text());                  //上词的平台

                    if (string.IsNullOrEmpty(platform))
                        platform = "0";         //找不到平台,用0代替

                    if (isFirst)
                    {
                        RemoveAttr(result);
                        isFirst = false;
                    }

                    //添加成功记录
                    AddSnap(page, userid, itemid, index, keyword, result.OuterHtml() + nums_html, platform, index_key);
                }
            }
        }

        protected override void RemoveAttr(Elements result)
        {

            Elements script = result.Select("script");
            script.Remove();

            Elements style = result.Select("style");
            style.Remove();

            Elements div = result.Select("div");
            div.RemoveAttr("click_area");
            div.RemoveAttr("name");
            div.RemoveAttr("ad_aid");
            div.RemoveAttr("data-max-line-expand");
            div.RemoveAttr("data-max-line");
            div.RemoveAttr("c-line-clamp");
            div.RemoveAttr("data-i");
            div.RemoveAttr("cpc_normal_idea");

            div.RemoveAttr("ad_seid");
            div.RemoveAttr("cpc_baokuanzt");
            div.RemoveAttr("ad_dot_url");
            div.RemoveAttr("data-sc");

            Elements ele = result.Select("a");
            ele.Attr("href", "#");
            ele.RemoveAttr("target");
            ele.RemoveAttr("name");
            ele.RemoveAttr("data-sc");
            ele.RemoveAttr("data-log");
            ele.RemoveAttr("data-recoorgi");
        }
    }
}